import com.google.gson.Gson;

import java.net.*;

/**
 * @ClassName: Receiver
 * @Description:
 * @Author: 12071
 * @Date: 2021/6/24 16:43
 */
public class UDPReceiver {
    public static void main(String[] args) throws Exception
    {
        @SuppressWarnings("resource")
        InetAddress address = InetAddress.getLocalHost();
        DatagramSocket ds = new DatagramSocket(8989, address); //接收端监听指定端口
        while(true)
        {
            //定义数据包,用于存储数据
            byte[] buf = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buf,buf.length);
            ds.receive(dp);//通过服务的receive方法将收到数据存入数据包中,receive()为阻塞式方法
            //通过数据包的方法获取其中的数据
            String ip = dp.getAddress().getHostAddress();
            String data = new String(dp.getData(),0,dp.getLength());
            Gson gson = new Gson();
            Position position = gson.fromJson(data,Position.class);
            System.out.println(ip+"::"+data);
            System.out.println("接收到的为"+position.toString());
        }
    }
}
